import React from 'react';
import { Upload, Modal,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AV from 'leancloud-storage'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    pathList:[],
    fileList: [
    //   {
    //     uid: '-1',
    //     name: 'image.png',
    //     status: 'done',
    //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //   },
    //   {
    //     uid: '-xxx',
    //     percent: 50,
    //     name: 'image.png',
    //     status: 'uploading',
    //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //   },
    //   {
    //     uid: '-5',
    //     name: 'image.png',
    //     status: 'error',
    //   },
    ],
  };
  handleUpload = async info=>{
        var newfile = {
            percent: 0,
            status: 'uploading',
        }
        var fileList = this.state.fileList
        fileList.push(newfile)
        this.setState({
            fileList
        })
        // console.log(info)
        let imageUrl = await getBase64(info.file)
        var fileList = this.state.fileList
        fileList[fileList.length-1].percent = 50
        this.setState({
            fileList
        })
        let data = {base64: imageUrl };
        const file = new AV.File('image.png', data);
        file.save().then(res=>{
            // console.log(res)
            let uid = res.id
            let {name,url} = res.attributes;
            let newfile = {uid,name,url,status:'done'}
            var fileList = this.state.fileList
            fileList.splice(fileList.length-1,1,newfile)
            this.setState({
                fileList,
                pathList:[...this.state.pathList,url]
            })
            this.props.handlePathList(this.state.pathList)
        }).catch(()=>{
            var fileList = this.state.fileList
            let uid = Math.random().toString(36).slice(2)+'dsafgfgjsasf'
            fileList.push({uid,name: 'image.png',status: 'error',})
            this.setState({
                fileList
            })
        })
  }
  handleRemove = (info)=>{
    let {uid} = info
    // const file = AV.File.createWithoutData(info.uid);
    // file.destroy();
    let fileList = this.state.fileList
    let pathList = this.state.pathList
    let len = fileList.length
    for(let i = 0; i < len; i++){
        if(fileList[i].uid === uid){
            fileList.splice(i,1)
            pathList.splice(i,1)
            break;
        }
    }
    this.setState({
        fileList,pathList
    })
    this.props.handlePathList(this.state.pathList)
  }
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

//   handleChange = ({ fileList }) => this.setState({ fileList });

  beforeUpload =(file) =>{
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          beforeUpload={this.beforeUpload}
          customRequest={this.handleUpload}
          onRemove = {this.handleRemove}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}
export default PicturesWall